<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
      </el-form-item>
      <el-table v-if="refreshTable" v-loading="loading" :data="list">
        <el-table-column :show-overflow-tooltip="true" label="编号" type="index" />
        <el-table-column :show-overflow-tooltip="true" label="字段名称">
          <template #default="scope">
            <div>
              <ns-input v-model="scope.row.name" placeholder="请输入字段名称" />
            </div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="填写方式" prop="fillingMethod">
          <template #default="scope">
            <div>
              <el-select
                v-model="scope.row.fillingMethod"
                placeholder="请选择填写方式"
                :disabled="scope.$index < 3"
              >
                <el-option label="输入框" value="输入框" />
                <el-option label="选择器" value="选择器" />
                <el-option label="日期" value="日期" />
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="预置内容" prop="presetContent">
          <template #default="scope">
            <!-- <div v-if="scope.$index !== 2"> -->
            <!-- 2024-12-26 只有输入框可以预置内容 -->

            <template v-if="scope.$index != 2">
              <el-tag
                v-for="(tag, tagIndex) in scope.row.presetContentMap"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleClose(tagIndex, scope.row.presetContentMap)"
              >
                {{ tag }}
              </el-tag>
              <ns-input
                v-if="scope.row.inputVisible && scope.row.fillingMethod == '选择器'"
                ref="InputRef"
                v-model="inputValue"
                class="w-20"
                size="small"
                @keyup.enter="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              />
              <el-button
                v-if="!scope.row.inputVisible && scope.row.fillingMethod == '选择器'"
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
              >
                +
              </el-button></template
            >

            <!-- </div> -->
            <div v-else>
              <el-select v-model="scope.row.presetContentMap" multiple placeholder="请选择">
                <el-option
                  v-for="item in levelList"
                  :key="item.levelCode"
                  :label="item.levelName"
                  :value="item.levelCode"
                />
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="关联其他标准字段">
          <template #default="scope">
            <div>
              <el-cascader
                v-model="scope.row.relevance"
                placeholder="请选择关联其他标准字段"
                :props="cascaderProps"
                :options="relevanceTree"
                filterable
                clearable
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="是否必填	">
          <template #default="scope">
            <div>
              <el-radio-group v-model="scope.row.required">
                <el-radio :label="1" size="large" :disabled="scope.row.display == 2">必填</el-radio>
                <el-radio :label="2" size="large">非必填</el-radio>
              </el-radio-group>
            </div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="是否显示">
          <template #default="scope">
            <div>
              <el-radio-group v-model="scope.row.display">
                <el-radio :label="1" size="large">显示</el-radio>
                <el-radio :label="2" size="large" :disabled="scope.row.required == 1"
                  >不显示</el-radio
                >
              </el-radio-group>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import { infoList, infoUpdateBatch, infoRelevanceTree } from '@/api/dataStandards/info/index'
import { levelPage } from '@/api/strategyManage/level/index'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const message = useMessage() // 消息弹窗
const route = useRoute()
const { t } = useI18n() // 国际化
const refreshTable = ref(true)
const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据

const inputValue = ref('')
const InputRef = ref()

const handleClose = (tagIndex, presetContentMap) => {
  presetContentMap.splice(tagIndex, 1)
}

const showInput = (row) => {
  row.inputVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = (row) => {
  if (inputValue.value) {
    row.presetContentMap.push(inputValue.value)
  }
  row.inputVisible = false
  inputValue.value = ''
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await infoList({
      dataStandardId: route.query.id
    })
    console.log('data', data)
    list.value = data.map((item) => {
      return {
        ...item,
        inputVisible: false,
        presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
      }
    })
  } finally {
    loading.value = false
  }
}

const save = async () => {
  const filteredList = list.value.filter(item => item.name)
  filteredList.map((item) => {
    item.presetContent = JSON.stringify(item.presetContentMap)
  })
  // console.log('list.value', list.value)
  const data = await infoUpdateBatch(filteredList)
  // console.log('data', data)
  if (data) {
    message.success('操作成功')
  }
}

const cascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})
const relevanceTree = ref()
const getInfoRelevanceTree = async () => {
  const data = await infoRelevanceTree()
  console.log('data123', data)
  relevanceTree.value = traverseTree(data)
  console.log('traverseTree(data)', traverseTree(data))
}
function traverseTree(data) {
  const updatedTree = []

  for (let i = 0; i < data.length; i++) {
    const node = data[i] // 创建新节点并添加 disable 属性
    if (node.pid == '-1') {
      node.disabled = true
    }
    updatedTree.push(node)

    if (node.children && node.children.length > 0) {
      node.children = traverseTree(node.children) // 递归遍历子节点并更新子树结构
    }
  }

  return updatedTree
}

// 获取等级下拉列表
const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  levelList.value = data
}

onMounted(() => {
  getList()
  getInfoRelevanceTree()
  getLevelList()
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
